import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';

import { partsOrderPayTypeArr } from '../order.pipe';
import { OrderAccService } from './order-acc.service';
import {PermissionService} from '../../../service/permission.service';
import { CommonService } from '../../../services-common/common.service'
@Component({
  selector: 'app-order-acc',
  templateUrl: './order-acc.component.html',
  styleUrls: ['./order-acc.component.scss']
})
export class OrderAccComponent implements OnInit {

  orderStateSet: any = { 2: '待付款', 3: '待审核', 4: '审核不通过', 5: '审核通过', 6: '排队发货', 7: '待发货', 8: '待收货(已发货)', 9: '交易完成', 10: '支付超时', 11: '客服取消', 12: '客户取消', 13: '售后中', 14: '全部退货', }
  /**
   * 跟进模态框
   */
  followVisible: boolean = false;
  /**
   * 跟进内容
   */
  followList: any = [];
  /**
   * 查询参数
   */
  queryForm: any = {
    // 商品名称
    goodsName: '',
    // 订单编号
    orderNum: '',
    // 关联回收单号
    renewalNo: '',
    // 汇款识别码
    transferCode: '',
    // 支付方式
    payTypeList: [],
    // 订单状态(暂定这几个后面会加) 0：有效1：无效2：待付款3：待发货4：已发货 5已收货 6已取消
    orderState: '',
    orderStateList: [],
    // 付款状态 (0、未付款 1、已付款 2、部分退款 3、全部退款)
    paymentState: '',
    // 售后状态 0：待审核，1：审核通过，2：审核未通过，3：已取消，4：已返款
    afterState: '',
    // 订单渠道
    platformList: [],
    // 来源平台
    sourcePlatform: '',
    // 推广渠道
    cidList: [],
    // 时间区间
    dateFormat: '',
    // 付款时间
    paymentTime: [],
    // 发货时间
    shipTime: [],
    // 完成时间
    completeTime: [],
    // 下单开始时间
    orderBeginTime: '',
    // 下单结束时间
    orderEndTime: '',
    // 付款开始时间
    paymentBeginTime: '',
    // 付款结束时间
    paymentEndTime: '',
    // 发货开始时间
    shipBeginTime: '',
    // 发货结束时间
    shipEndTime: '',
    // 完成开始时间
    dealBeginTime: '',
    // 完成结束时间
    dealEndTime: '',
    // 用户名或手机号码
    user: '',
    // 用户类型：1-C端用户、2-B端商户
    userTypes: '',
    // 物流单号
    expressNo: '',
    // 货主
    supplierIdList: [],
    // 页数
    page: 1,
    // 条数
    pageSize: 20,
  };
  /**
   * 跟进参数
   */
  followParam: any = {
    // 关联信息(订单号 售后单号 客户id 出库单号)
    relationInformation: "",
    // 1、订单 2、售后 3、客户 4、出库
    type: 1,
    // 文件列表
    enclosure: [],
    // 备注
    content: "",
    // 当前页
    page: 1,
    // 当天加载条数
    pageSize: 10
  }
  /**
   * 列表数据
   */
  listOfData?: any;

  /**
   * 当前是否在搜索
   */
  searchHint = false;
  /**
   * 表格是否加载中
   */
  tableLoading: any = false;
  /**
   * 当前搜索name
   */
  searcName = "";
  /**
   * 是否全选
   */
  checked = false;
  /**
   * 审核意见
   */
  auditDesc = "";
  /**
   * 全局 loading
   */
  messageId: any = null;
  /**
   * 已选择订单
   */
  selectArr: any = [];
  /**
   * 导出信息模态框
   */
  exportVisible = false;
  isVisible = false;
  /**
   * 时间选择器
   */
  exportDate = null;
  /**
   * 模态框参数
   */
  modalParam: any = {};
  /**
   * 上传val
   */
  inputVal: any = null;
  /**
   * 加载失败显示图像占位符
   */
  fallback =
    '';

  /**
   * 路由缓存恢复时
   */
  static updateCache: any = null;
  // 弹窗 跟进记录
  modalTable: any = {
    // 列表集合
    records: [],
    // 总条数
    total: 0
  }

  // 渠道下拉
  channelSelects: any = [];

  // 用户身份selected
  userTypeSelected: Array<any> = [];

  // 子订单弹窗
  isChildVisible: boolean = false;
  // 子订单table
  childTableData: any = [];

  // seach 展开收起
  isCollapse: boolean = false;

  // 订单来源
  orderSourceOptions: any = [];
  scurceSelected: any = [];
  // 推广渠道list
  extensionOptions: any = [];

  // 货主options
  supplierOptions: any = [];

  // 支付方式Options
  payTypeOptions: any = [...partsOrderPayTypeArr];

  /**
   * 快捷筛选
   * 待操作订单————3:待审核、7:待发货、6:排队发货、5:审核通过
   * 有效订单————2:待付款、3:待审核、5:审核通过、6:排队发货、7:待发货、8:待收货、9:交易完成
   * ----------------------------------------------------------------------------------------------------
   */
  quickScreenStatus: any = [
    {value: '', label: '全部'},
    {value: '3,5,6,7', label: '待操作订单'},
    {value: '2,3,5,6,7,8,9', label: '有效订单'}
  ];
  quickScreenSelected: string = '';

  constructor(
    private router: Router,
    private OrderAccService: OrderAccService,
    private message: NzMessageService,
    private fb: FormBuilder,
    public permission: PermissionService,
    private commonService: CommonService,
    private nzModalService: NzModalService
  ) { }

  ngOnInit() {
    OrderAccComponent.updateCache = () => {
      this.getChannelData(); // 渠道
      this.queryExtension(); // 查询 推广渠道
      this.queryPlatfrom(); // 查询 订单来源平台(自营、淘宝等...)
      this.querySupplierOptions(); // 货主(供货商)
      this.tableLoading = false;
      this.getList();
    }
    
    this.getChannelData(); // 渠道
    this.queryExtension(); // 查询 推广渠道
    this.queryPlatfrom(); // 查询 订单来源平台(自营、淘宝等...)
    this.querySupplierOptions(); // 货主(供货商)
    this.getList();
  }

  // 查询 订单来源平台
  async queryPlatfrom() {
    this.orderSourceOptions = await this.commonService.getDictList('order_source_platform');
  }
  // 查询 推广渠道
  async queryExtension() {
    this.extensionOptions = await this.commonService.getDictList('iDiy_extension_channel');
  }
  // 查询 货主（供货商）
  async querySupplierOptions() {
    this.supplierOptions = await this.commonService.getSupplierList();
  }

  toTabs(id: any) {
    // this.queryForm.searchType = id;
    this.getList();
  }
  // 页码改变
  onPageIndexChange(index: number) {
    console.log(index);
    this.queryForm.page = index;
    this.checked = false;
    this.getList();
  }
  // 每页条数改变的回调
  onPageSizeChange(index: number) {
    console.log(index);
    this.queryForm.pageSize = index;
    this.checked = false;
    this.getList();
  }
  /**
   * 查询
   */
  query() {
    this.queryForm.page = 1;
    this.getList();
  }
  // 重置
  resetData() {
    for (let key in this.queryForm) {
      if (Array.isArray(this.queryForm[key])) {
        this.queryForm[key] = [];
      } else {
        this.queryForm[key] = '';
      }
    }
    this.userTypeSelected = [];
    this.scurceSelected = [];
    this.quickScreenSelected = ''; // 快捷筛选

    this.queryForm.page = 1;
    this.queryForm.pageSize = 20;
    this.getList();
  }

  /**
   * 获取列表数据
   * @returns
   */
  getList() {
    if (this.tableLoading) { return; }
    this.listOfData = [];
    this.tableLoading = true;
    this.createBasicMessage()
    this.OrderAccService.get(this.queryForm).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.tableLoading = false;
        this.createMessage("error", res.message);
        return;
      }
      res.data.records.forEach((element: any) => {
        element['Checked'] = false;
      });
      this.listOfData = res.data;

      for (let index = 0; index < this.listOfData.records.length; index++) {
        let element = this.listOfData.records[index];
        element.statusTest = this.status_To_Text(element.status);

      }
      let textArr = [];
      if (this.queryForm.goodsName) {
        textArr.push(this.queryForm.goodsName);
      }
      if (this.queryForm.orderNum) {
        textArr.push(this.queryForm.orderNum);
      }
      if (this.queryForm.orderState) {
        textArr.push(this.status_To_Text(this.queryForm.orderState));
      }
      if (this.queryForm.dateFormat) {
        let strTime = this.OrderAccService.shiftDate(this.queryForm.dateFormat[0]);
        let endTime = this.OrderAccService.shiftDate(this.queryForm.dateFormat[1]);
        let time = strTime + " - " + endTime;
        textArr.push(time);
      }
      this.searcName = textArr.join(' | ');

      this.tableLoading = false;
    }, err => {
      this.removeBasicMessage();
      this.tableLoading = false;
      this.createMessage("error", err.message);
    });
  }
  /**
   * 搜索返回原列表,
   */
  backList() {
    this.queryForm.goodsName = "";
    this.queryForm.user = "";
    this.queryForm.platformList = [];
    this.queryForm.userTypes = '';
    this.userTypeSelected = [];
    this.queryForm.orderNum = "";
    this.queryForm.orderState = "";
    this.queryForm.dateFormat = "";
    this.queryForm.paymentTime = [];
    this.queryForm.paymentBeginTime = '';
    this.queryForm.paymentEndTime = '';
    this.queryForm.completeTime=[]
    this.queryForm.dealBeginTime = ''
    this.queryForm.dealEndTime = ''
    this.queryForm.orderStateList = [];
    this.queryForm.page = 1;

    this.searchHint = false;
    this.getList();
  }

  /**
   * 审核保存
   */
  save(state: any) {
    if (this.messageId != null) {
      return;
    }
    let ids = this.selectArr.map((ele: any) => {
      return ele.id
    });
    if (ids.length == 0) {
      return this.createMessage("warning", "请选择要审核的订单");
    }
    if (state == 4 && !this.auditDesc) {
      return this.createMessage("warning", "请输入审核意见");
    }
    let json = {
      ids: ids,
      //审核状态 4:不通过 5:通过
      state: state,
      // 审核意见
      auditDesc: this.auditDesc,
      type: 0
    }
    this.createBasicMessage();
    this.OrderAccService.audit(json).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage(res.code === 999 ? "warning" : "error", res.message);
        return;
      }
      this.createMessage("success", res.message);
      this.handleCancel();
      this.getList();
    }, err => {
      this.removeBasicMessage();
      this.createMessage("error", err.message);
    });
  }
  /**
   * 状态转换颜色
   */
  getStatusColor(s: any) {
    let colorText = "";
    switch (parseInt(s)) {
      // 红色
      case 2: case 10: case 11: case 12: case 14:
        colorText = "font2"
        break;
      // 橙色
      case 3: case 6: case 13:
        colorText = "font3"
        break;
      // 灰色
      case 4:
        colorText = "font3"
        break;
      // 绿色
      case 5: case 9:
        colorText = "font3"
        break;

    }
    return colorText;
  }
  /**
   * item单选
   * @param id
   * @param checked
   */
  onItemChecked(id: number, checked: boolean): void {
    const index = this.listOfData.records.findIndex((item: { id: number; }) => item.id === id);
    this.listOfData.records[index].Checked = checked;
    this.updataCheckAll();
  }
  /**
   * 全选
   * @param value
   */
  onAllChecked(value: boolean): void {
    this.listOfData.records.forEach((item: any) => {
      if (item.statusTest == "待审核") {
        item.Checked = value
      }

    });
  }
  // 全选 订单状态
  onSelectAll(ev: any) {
    if (ev.includes('all')) {
      this.queryForm.orderStateList = Object.keys(this.orderStateSet)
    }
  }
  /**
   * 判断item是否全部选择
   */
  updataCheckAll() {
    const index = this.listOfData.records.findIndex((item: { Checked: boolean; }) => item.Checked == false);
    if (index != -1) {
      this.checked = false;
    } else {
      this.checked = true;
    }
  }
  /**
   * 物流编码转文字
   */
  expressCode_To_Text(s: any) {
    let test = "";
    switch (s) {
      case "SF":
        test = "顺丰";
        break;
      case "YTO":
        test = "圆通";
        break;
      case "ZTO":
        test = "中通";
        break;
      case "STO":
        test = "申通";
        break;
      case "YD":
        test = "韵达";
        break;
      case "JD":
        test = "京东";
        break;
      default:
        test = "-";
        break;
    }
    return test;
  }
  /**
   * 打开模态框(导出信息)
   * s 1：主信息，2：明细
   */
  exportModal(s: any) {
    // this.exportVisible = true;
    this.modalParam.exportCode = s;
    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: '<b style="color: red;">即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制时间范围。确定导出？</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.exportOrder();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
  /**
   * 打开模态框(审核)
   */
  showModal(obj: any = null) {
    this.isVisible = true;
    this.selectArr = this.listOfData?.records?.filter(function (item: any) {
      return obj ? obj.id == item.id : item.Checked == true
    })
  }


  /**
   * 关闭模态框
   */
  handleCancel() {
    this.isVisible = false;
    this.exportVisible = false;

    this.exportDate = null;
    this.followVisible = false;

    this.auditDesc = '';
    this.followParam.content = "";
    this.followParam.enclosure = [];
    this.followParam.relationInformation = ''
  }
  /**
   * 删除跟进图片
   */
  deleteFollowImg(index: any) {
    this.inputVal = null;
    this.followParam.enclosure = this.followParam.enclosure.filter((item: any, i: any) => {
      return i != index;
    });
  }
  /**
   * 打开模态框(跟进) 初始化
   * @param id
   */
  followModal(relationInformation: any): void {
    this.followParam.relationInformation = relationInformation;
    this.followVisible = true
  }

  /**
   * 跳转调节单
   */
  toAdjustOrder() {
    this.router.navigate(['service/newAdjustOrder']);
  }
  /**
   * 导出
   */
  exportOrder() {
    // if (!this.exportDate) {
    //   return this.createMessage("warning", "请选择时间");
    // }
    if (this.messageId != null) {
      return;
    }
    this.createBasicMessage();
    this.OrderAccService.export({ ...this.queryForm, exportCode: this.modalParam.exportCode }).subscribe((res: any) => {
      this.removeBasicMessage();
    }, err => {
      this.removeBasicMessage();
      // this.createMessage("error", err.message);
      if (err.status == 200) {
        window.open(err.url, '_self')
        this.handleCancel();
      }
      // console.log(err);
    });
  }
  /**
   * 批量发货
   */
  goodsDeliver() {
    if (this.messageId != null) {
      return;
    }
    let ids = this.listOfData.records.filter(function (item: any) { return item.status == 5; })
    if (ids.length == 0) {
      return this.createMessage("warning", "当前列表没有需要发货的订单");
    }
    let json = {
      state: 5,
      type: 1
    }
    this.createBasicMessage();
    this.OrderAccService.audit(json).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage("error", res.message);
        return;
      }
      this.createMessage("success", "批量发货成功");
      this.getList();
    }, err => {
      this.removeBasicMessage();
      this.createMessage("error", err.message);
    });
  }
  /**
   * 文件上传完成回调
   * @param files
   * @param type  1:图片信息 2:视频文件 3:视频封面
   */
  handleFileInput(files: any, type: any) {
    let fileArr = files.target.files;
    for (let index = 0; index < fileArr.length; index++) {
      const element = fileArr[index];
      this.postFile(element, this.splitFileName(element.name), (res: any) => {
        if (res.code != 0) {
          return;
        }
        // 上传类型
        if (type == 2) {
          this.followParam.enclosure.push({
            // 显示地址
            showUrl: element.name,
            // 图片地址
            url: res.data,
          });
        }
        this.inputVal = null;
      });
    }
  }
  /**
   * 新增跟进
   */
  followerSave() {
    if (this.messageId != null) {
      return;
    }
    if (!this.followParam.content) {
      return this.createMessage("warning", "请输入备注");
    }
    this.createBasicMessage();
    this.OrderAccService.followerSave(this.followParam).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage("error", res.message);
        return;
      }
      this.handleCancel();
      this.createMessage("success", "跟进信息成功");
    }, err => {
      this.removeBasicMessage();
      this.createMessage("error", err.message);
    })
  }
  /**
   * 上传文件
   * @param fileName
   * @param su 上传完成回调函数
   */
  postFile(file: any, fileName: string, su: any) {
    this.OrderAccService.postFile(file, fileName).subscribe(data => {
      if (su) su(data);
    }, error => {

    });
  }
  /**
   * 订单状态转换
   * 0：有效1：无效2：待付款3：待发货4：已发货 5已收货 6已取消
   * @param s
   * @returns
   */
  status_To_Text(s: any) {
    let test = "";
    s = parseInt(s);
    switch (s) {
      case 0:
        test = "有效";
        break;
      case 1:
        test = "无效";
        break;
      case 2:
        test = "待付款";
        break;
      case 3:
        test = "待审核";
        break;
      case 4:
        test = "审核不通过";
        break;
      case 5:
        test = "审核通过";
        break;
      case 6:
        test = "排队发货";
        break;
      case 7:
        test = "待发货";
        break;
      case 8:
        test = "待收货(已发货)";
        break;
      case 9:
        test = "交易完成";
        break;
      case 10:
        test = "支付超时";
        break;
      case 11:
        test = "客服取消";
        break;
      case 12:
        test = "客户取消";
        break;
      case 13:
        test = "售后中";
        break;
      case 14:
        test = "全部退货";
        break;
      default:
        test = "---";
        break;
    }
    return test;
  }

  // 查看子订单
  viewChildModel(item: any) {
    this.childTableData = [];
    this.childTableData = item.oldList;
    this.isChildVisible = true;
  }
  // 子订单跟进
  childFollow(item: any) {
    this.followModal(item.orderNum);
    // this.isChildVisible = false;
  }
  // 子订单跳转详情
  childDetail(item: any) {
    this.isChildVisible = false;
    setTimeout(() => {
      this.router.navigate(['/order/accDetails', item.id]);
    }, 200);
  }
  // handleChildCancel
  childCancel() {
    this.isChildVisible = false;
  }

  // 获取渠道（字典）
  async getChannelData() {
    try {
      const res: any = await this.OrderAccService.dictData('channel');
      this.channelSelects = res.data.list.records || [];
    } catch {
      // console.log('errro')
    }
  }

  // 上传文件夹字符串截取
  splitFileName(text: string) {
    var pattern: any = /\.{1}[a-z]{1,}$/;
    if (pattern.exec(text) !== null) {
      return (text.slice(0, pattern.exec(text).index));
    } else {
      return text;
    }
  }

  // 删除
  async deleteItemData(item: any) {
    try {
      let params = {
        id: item.id,
        orderNum: item.orderNum // 订单号
      }
      
      const res: any = await this.OrderAccService.orderDeleteItem(params);
      if (res.code == 0) {
        this.message.success('删除成功');
        this.getList();
      } else {
        this.message.error(res.message || '删除失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 用户身份select change
  userTypeChange(result: any) {
    this.queryForm.userTypes = result.join(',');
  }

  // 下单次数查询
  quantityNumSearch(item: any) {
    if (!item?.numberCount) {
      return
    }
    this.queryForm.user = item?.userId || item.tel;
    this.queryForm.page = 1;
    this.getList();
  }

  /**
   * 开启loading
   */
  createBasicMessage(): void {
    this.messageId = this.message.loading('正在请求...', { nzDuration: 0 }).messageId;
  }
  /**
   * 移除loading
   */
  removeBasicMessage() {
    this.message.remove(this.messageId);
    this.messageId = null;
  }
  /**
   * 全局展示操作反馈信息
   * @param type 其他提示类型 success:成功 error:失败 warning：警告
   */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }

  // 审核合并发货
  examineMerge() {
    if (this.selectArr?.length < 2) {
      this.message.warning('请至少选择两个订单');
      return
    }
    // 收货人相同 & 联系电话相同 & 地址相同
    if (!this.isJudgeArr('consignee') || !this.isJudgeArr('tel') || !this.isJudgeArr('address')) {
      this.message.warning('用户收货信息不一致，无法合并发货');
      return
    }
    // 订单的货主要相同
    if (!this.isJudgeArr('supplierId')) {
      this.message.warning('订单货主不同，无法合并发货');
      return
    }
    // 订单的来源平台要相同
    if (!this.isJudgeArr('sourceType')) {
      this.message.warning('订单来自不同的来源平台，无法合并发货');
      return
    }
    
    let ids = this.selectArr.map((ele: any) => ele.id);
    let params = {
      ids: ids,
      //审核状态 4:不通过 5:通过
      state: 5,
      // 审核意见
      auditDesc: this.auditDesc,
      type: 0,
      isMerge: 0
    }
    this.OrderAccService.audit(params).subscribe((res: any) => {
      if (res.code === 0) {
        this.isVisible = false;
        this.message.success('操作成功');
        this.getList();
      } else {
        this.message.error(res.message);
      }
    })
  }

  isJudgeArr(filterStr: string) {
    let tmpArrs = false;
    tmpArrs = this.selectArr.every((item: any) => {
      return item[filterStr] === this.selectArr[0][filterStr];
    });
    return tmpArrs;
  }

  /**
   * Dict类型转化文字
   * @returns
   */
  dictTextFilter(typeVal: String, arr: any) {
    let tmpObj: any = {};
    if (arr && arr.length) {
      tmpObj = arr.find((item: any) => item.content == typeVal);
    }

    return tmpObj?.name || '-';
  }

  // 订单来源平台change
  multipleChange(arrs: any, key: string) {
    this.queryForm[key] = arrs.join(',');
  }

  // 确认收款(支付方式：对公、订单状态：待付款)
  confirmCollection(item: any) {
    this.nzModalService.confirm({
      nzTitle: '提示?',
      nzContent: '确认收款?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        const res: any = await this.OrderAccService.confirmCollectionData(item.id);
        if (res.code === 0) {
          this.message.success('操作成功');
          this.getList();
        } else {
          this.message.error(res.message);
        }
      },
      nzCancelText: '取消'
    });
  }

  // 快捷选择筛选
  quickScreenChange(val: any) {
    this.queryForm.orderStateList = val ? val.split(',') : [];
    this.queryForm.page = 1;
    this.getList();
  }
}
